package tee;


import java.security.SecureRandom;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

public class RandomUtil {

    public static String create32Uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String create16Uuid() {
        String s = UUID.randomUUID().toString().replaceAll("-", "");
        return s.substring(0, 16);
    }

    public static String createJobToken() {
        return Long.toHexString(System.currentTimeMillis()) + RandomUtil.create32Uuid();
    }

    // 检查jobId长度是否超出数据库字段设置
    public static String createJobId(String prefix) {
        return prefix + create32Uuid();
    }

    public static String createJobId() {
        return createJobId("");
    }

    /**
     * 生成指定长度的job id 可以指定前缀
     */
    public static String createJobId(String prefix, int length) {
        StringBuffer sb = new StringBuffer();
        sb.append(prefix);
        sb.append("_");
        while (sb.length() < length) {
            sb.append(create32Uuid());
        }
        return sb.substring(0, length);
    }

    /**
     * 构建虚拟数据集Id
     *
     * @return
     */
    public static String createVirtualId() {
        return create32Uuid();
    }

    /**
     * 随机获得一个实例
     *
     * @param objectSet
     * @return
     */
    public static Object randomEntry(Set<Object> objectSet) {
        if (null == objectSet || objectSet.isEmpty()) {
            return null;
        }
        List<Object> objectList = objectSet.stream().collect(Collectors.toList());
        int index = (int) (new SecureRandom().nextFloat() * objectList.size());
        return objectList.get(index);
    }
}
